using System;
using Habanero.Base;
using Habanero.Base.Exceptions;

namespace FireStarterModeller.BO
{
    /// <summary>
    /// With Single Table Inheritance the SubClasses are stored in the same table as the 
    /// SuperClass and therefore should not have their own PrimaryKey.
    /// </summary>
    public class DMSingleTableInheritanceSubClassShouldNotHaveObjectIdentity : IBusinessObjectRule
    {
        private DMInheritanceRelationship _inheritanceRelationship;

        [Obsolete("Use IsValid(IBusinessObject bo) instead")]
        public bool IsValid()
        {
            throw new HabaneroApplicationException(
                "The IsValid is no longer Valid you should use the IsValid(bo) method");
        }

        /// <summary>
        /// Indicates whether the property value is valid against the rules
        /// </summary>
        /// <returns>
        /// Returns true if valid
        /// </returns>
        public bool IsValid(IBusinessObject bo)
        {
            _inheritanceRelationship = bo as DMInheritanceRelationship;
            if (_inheritanceRelationship == null) return true;

            if (_inheritanceRelationship.SubClass == null) return true;
            if (_inheritanceRelationship.InheritanceType != ORMapping.SingleTableInheritance) return true;
            
            if( _inheritanceRelationship.SubClass.ObjectIdentity == null) return true;
            return _inheritanceRelationship.SubClass.ObjectIdentity.Properties.Count == 0;
        }

        /// <summary>
        /// Returns the rule name
        /// </summary>
        public string Name
        {
            get { return GetType().Name; }
        }

        /// <summary>
        /// Returns the error message for if the rule fails.
        /// </summary>
        public string Message
        {
            get
            {
                var messageStart
                    = string.Format(
                        "The Single Table Inheritance relationship is invalid. The SubClass '{0}' should not have a PrimaryKeyDefined/ObjectIdentifier.",
                        SubClassName());
                const string messageEnd
                    =  "(With Single Table Inheritance the SubClasses are stored in the same table as the SuperClass and therefore should not have their own PrimaryKey)";
                return messageStart + Environment.NewLine + messageEnd;
            }
        }

        private string SubClassName()
        {
            return _inheritanceRelationship == null? "": _inheritanceRelationship.SubClassName;
        }

        /// <summary>
        /// The <see cref="P:Habanero.Base.IBusinessObjectRule.ErrorLevel"/> for this BusinessObjectRule e.g. Warning, Error. 
        /// </summary>
        public ErrorLevel ErrorLevel
        {
            get { return ErrorLevel.Error; }
        }
    }
}